#!/bin/bash
set -e

function pack_img {
	# error checks
	if [ -e "${1}" ] ; then
		echo "Error. File ${1} already exists!"
		exit 1
	fi
	if [ ! -d unpack_update ] ; then
		echo "Error. No unpack_update folder found."
		exit 1
	fi
	if [ ! -d source_img ] ; then
		echo "Error. No source_img folder found."
		exit 1
	fi

	img_file=$(basename "${1}")
	img_path=$(dirname "${1}")

	echo "****** Packing to ${img_file}"
	mv source_img unpack_update/Image
	BOOTLOADER=$(awk '$1=="bootloader" {print $2}' unpack_update/package-file)
	BOOTLOADER=$(echo $BOOTLOADER | tr -d '\r')
	afptool -pack unpack_update update.img
	img_maker "unpack_update/${BOOTLOADER}" update.img "${1}"
	mv unpack_update/Image source_img
	rm -f update.img

	echo "****** Done."
	echo ""
	echo ""
}


function unpack_img {
	# error checks...
	if [ ! -n "${1}" ] ; then
		usage
		exit 0
	fi
	if [ ! -f "${1}" ] ; then
		echo "Error. File ${1} doesn't exist!"
		exit 1
	fi
	# check magic
	magic=`head -c 4 "${1}"`
	if [ "${magic}" != "RKFW" ] ; then
		echo "Error. File ${1} is not a proper rk_update image img! Header magic is '${magic}' but should be 'RKFW'."
		exit 1
	fi

	img_file=$(basename "${1}")
	img_path=$(dirname "${1}")

	echo "****** Cleaning dev folders"
	rm -rf source_img
	rm -rf unpack_update

	echo "****** Unpacking ${img_file} to unpack_update/"
	img_unpack "${1}" update.img
	afptool -unpack update.img unpack_update
	rm -f update.img
	mv unpack_update/Image source_img

	echo "****** Done."
	echo ""
	echo ""
}

function usage {
	echo "Usage: ${0} -p <rk_update.img>     # to create rk_update package"
	echo "       ${0} -u <rk_update.img>     # to unpack rk_update package"
}



while getopts "p:u:" opt; do
	case $opt in
	p)
		pack_img "${OPTARG}"
		exit 0
		;;
	u)
		unpack_img "${OPTARG}"
		exit 0
		;;
	\?)
		echo "Error. Invalid option: ${OPTARG}" >&2
		usage
		exit 1
		;;
	:)
		echo "You need to add <rk_update.img> argument." >&2
		exit 1
		;;
	esac
done

usage
